package org.ahead4.joint.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;


/**
 * <p>Description: AES算法加密/解密工具类</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Company: </p>
 * @author wangyu
 * @version 1.0
 */
public class AESUtils {

	public static void main(String[] args) throws Exception {  
        String content = "！@#￥%……&*（）【】、·~-=+法";  
        System.out.println("加密前：" + content+"||"+content.length());  
        
        String key = "123123123";  
        System.out.println("加密密钥和解密密钥：" + key);  
        String encrypt = Encrypt(content, key);  
        //String encrypt = "tRctmr0jer1nh2rdNvYFY7oqrxwJx4Mvfilcy+SQ4rEFlw63phnvPYMKQ2wExp1j";
        System.out.println("加密后：" + encrypt);  
        
        String decrypt = Decrypt(encrypt, key);  
        System.out.println("解密后：" + decrypt);  
    }
  
      
	/**
     * 提供密钥和向量进行加密
     * 
     * @param sSrc
     * @param key
     * @param iv
     * @return
     * @throws Exception
     */
    public static String Encrypt(String sSrc, byte[] key, byte[] iv) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
        IvParameterSpec _iv = new IvParameterSpec(iv);// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, _iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(encrypted);
    }

    /**
     * 提供密钥和向量进行解密
     *
     * @param sSrc
     * @param key
     * @param iv
     * @return
     * @throws Exception
     */
    public static String Decrypt(String sSrc, byte[] key, byte[] iv) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec _iv = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, _iv);
        byte[] encrypted = Base64.decodeBase64(sSrc);
        byte[] original = cipher.doFinal(encrypted);
        return new String(original, StandardCharsets.UTF_8);
    }

    /**
     * 使用密钥进行加密
     * 
     * @param sSrc
     * @param keyStr
     * @return
     * @throws Exception
     */
    public static String Encrypt(String sSrc, String keyStr) throws Exception {
        byte[] key = GeneralKey(keyStr);
        
        byte[] iv = GeneralIv(keyStr);
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
        IvParameterSpec _iv = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, _iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(encrypted);
    }

    /**
     * 使用密钥进行解密
     * 
     * @param sSrc
     * @param keyStr
     * @return
     * @throws Exception
     */
    public static String Decrypt(String sSrc, String keyStr) throws Exception {
        byte[] key = GeneralKey(keyStr);
        byte[] iv = GeneralIv(keyStr);
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec _iv = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, _iv);
        byte[] encrypted = Base64.decodeBase64(sSrc);// 先用base64解码
        byte[] original = cipher.doFinal(encrypted);
        return new String(original, StandardCharsets.UTF_8);
    }

    /**
     * 构建密钥字节码
     *
     * @param keyStr
     * @return
     * @throws Exception
     */
    private static byte[] GeneralKey(String keyStr) throws Exception {
        byte[] bytes = keyStr.getBytes(StandardCharsets.UTF_8);
        // 这里原算法为SHA-256，因为美国对软件出口的控制，只能使用128位算法故改成MD5
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(bytes);
        return md.digest();
    }

    /**
     * 构建加解密向量字节码
     *
     * @param keyStr
     * @return
     * @throws Exception
     */
    private static byte[] GeneralIv(String keyStr) throws Exception {
        byte[] bytes = keyStr.getBytes(StandardCharsets.UTF_8);
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(bytes);
        return md.digest();
    }
    
  
    private AESUtils() {
  
    }  
  
}
